#include <stdio.h>
#include "tcp_config.h"
#include "Com_format.h"
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "serial.h"
#include "cam.h"
#include "drive.h"
#include "Com_tcp.h"
#include "callback.h"
#include "select.h"

volatile struct activate_car data_car;
volatile int data_car_update = 0;
volatile struct trumpet data_trumpet;
volatile int data_trumpet_update = 0;

pthread_mutex_t data_trumpet_mutex;
pthread_mutex_t data_car_mutex;

int main()
{
    //初始化锁
    pthread_mutex_init(&data_trumpet_mutex, NULL);
    pthread_mutex_init(&data_car_mutex, NULL);
    int sockfd = getSocketfd(SERVER_IP, PORT); //连接服务器，返回套接字
    if (sockfd == -1)
    {

        // perror("socket failed");
        return -1;
    }

    printf("连接成功\n");

    //连接成功之后发送标识
    firstsignal(sockfd);

//开一个线程来处理小车的行动
    pthread_t pid_car;
    if (0 != pthread_create(&pid_car, NULL, car_callback, NULL))
    {
        perror("pthread_create");
        return -1;
    }

    //开一个线程来处理喇叭，要用到队列(以后写)
    pthread_t pid_trumpet;
    if (0 != pthread_create(&pid_trumpet, NULL, trumpet_callback, NULL))
    {
        perror("pthread_create");
        return -1;
    }

    //开一个线程来接收服务器的命令
    struct pthread_data data;
    data.sockfd = sockfd;
    pthread_t pid_recv;
    if (0 != pthread_create(&pid_recv, NULL, recv_callback, (void *)&data))
    {
        perror("pthread_create");
        return -1;
    }

    pthread_detach(pid_recv);
    pthread_detach(pid_car);
    pthread_detach(pid_trumpet);
    //select 执行
    my_select(sockfd);
    return 0;
}
